# -*- coding:utf-8 -*-
# @Author:Cheng Lei 1037654919@qq.com
# @Time : 2023/4/3 下午3:21
# @FileName: kuwo_t6_song_info.py.py
# @Software: PyCharm

# 第六步 获取所有歌曲信息


from multiprocessing import Pool
from class_kuwo import Kuwo
kuwo = Kuwo()
from utils import MongoDBUtil, get_html, mongo_manager
MongoDBUtil = MongoDBUtil()
playlist_tag = mongo_manager("playlist_tag", db="kuwo")
playlist_song= mongo_manager("playlist_song", db="kuwo")
singer_song= mongo_manager("singer_song", db="kuwo")
playlist_song_list= mongo_manager("playlist_song_list", db="kuwo")
song_info = mongo_manager("song_info", db="kuwo")



# 基于歌单更新歌曲列表
def playlist_song_list_run():
    seeds = playlist_song.findAll({"status": None})
    lists =[]
    for seed in seeds:
        lists.append(seed)
    print('playlist_song_list None:',len(lists))
    for seed in seeds:
        result ={"_id" : seed['rid']}
        try:
            # print(data)
            MongoDBUtil.insert_one('playlist_song_list', result)
        except Exception as e:
            print(e)
        seed['status']='success'
        playlist_song.updateOne({'_id': seed['_id']}, seed)
# 基于歌手更新歌曲列表
def singer_song_list_run():
    seeds = singer_song.findAll({"status": None})
    lists =[]
    # for seed in seeds:
    #     lists.append(seed)
    # print('singer_song_list_run None:',len(lists))
    for seed in seeds:
        result ={"_id":seed['rid']}
        try:
            # print(data)
            MongoDBUtil.insert_one('playlist_song_list', result)
        except Exception as e:
            print(e)
        seed['status']='success'
        singer_song.updateOne({'_id': seed['_id']}, seed)

# 插入数据
def insert_data(tablename, datas):
    if len(datas) > 0 and datas is not None:
        for data in datas:
            # data['_id'] = data['id']
            try:
                # print(data)
                MongoDBUtil.insert_one(tablename, data)
            except Exception as e:
                print(e)
    else:
        pass


# 解析歌曲信息
def parse_song(data):
    datas = data
    result = {'_id': datas.get("rid"), 'musicrid': datas.get("musicrid"),
              'name': datas.get("name"), 'score100': datas.get("score100"),
              'img': datas.get("pic"), 'album': datas.get("album"),
              'albumid': datas.get("albumid"), 'albuminfo': datas.get("albuminfo"),
              'albumpic': datas.get("albumpic"),'artist': datas.get("artist"),
              'artistid': datas.get("artistid"), 'barrage': datas.get("barrage"),
              'content_type': datas.get("content_type"), 'duration': datas.get("duration"),
              'hasLossless': datas.get("hasLossless"), 'hasmv': datas.get("hasmv"),
              'isListenFee': datas.get("isListenFee"), 'isstar': datas.get("isstar"),
              'mvPlayCnt': datas.get("mvPlayCnt"), 'mvUpPcStr': datas.get("mvUpPcStr"),
              'online': datas.get("online"), 'originalsongtype': datas.get("originalsongtype"),

              'releaseDate': datas.get("releaseDate"),
              'songTimeMinutes': datas.get("songTimeMinutes"), 'tme_musician_adtype': datas.get("tme_musician_adtype"),
              'track': datas.get("track"), 'upPcStr': datas.get("upPcStr")
              }
    return result


# 获取歌曲信息
def get_music_info(seed):
    playlist_song_list = mongo_manager("playlist_song_list", db="kuwo")
    song_info = mongo_manager("song_info", db="kuwo")
    mid = seed['_id']
    datas = kuwo.get_music_info(mid=mid)
    results = parse_song(datas)
    lyric = kuwo.get_song_lyric(mid=mid)  # list
    results['lyric'] = lyric
    try:
        song_info.insertOne(results)
        # insert_data(tablename='song_info', datas=[results])
        print("插入成功数据:",results["_id"])
    except Exception as e:
        print("error:",e)
    seed['status'] = 'success'
    playlist_song_list.updateOne({'_id': seed['_id']}, seed)
    playlist_song_list.close()
    song_info.close()
    # return seeds
def parse_singer_songs(data):
    datass = data['list']
    results=[]
    for datas in datass:
        result = {'_id': str(datas.get("artistid"))+'_'+str(datas.get("rid")),
                  'musicrid': datas.get("musicrid"),
                  'artist': datas.get("artist"),
                  'artistid': datas.get("artistid"),
                  'releasedate': datas.get("releasedate"),
                  'albumid': datas.get("albumid"),
                  'rid': datas.get("rid")
                  }
        results.append(result)
    return results

# 获取歌曲信息
def get_music_info_20230512(seed):
    song_info_20230512= mongo_manager("song_info_20230512", db="kuwo")
    mid = seed['_id']
    datas = kuwo.get_music_info(mid=mid)
    results = parse_song(datas)
    lyric = kuwo.get_song_lyric(mid=mid)  # list
    results['lyric'] = lyric
    try:
        # insert_data(tablename='song_info_20230512', datas=[results])
        song_info_20230512.insertOne(results)
        print("插入成功数据:", results["_id"])
    except Exception as e:
        print("error:",e)
    song_info_20230512.close()

def test_20230512(artist):
    seeds = song_info.findOne({"artist": artist})
    print(artist, seeds['artistid'])
    if seeds['artistid']:
        for page in range(1, 4):
            try:
                datas = kuwo.get_artist_Music(artistid=seeds['artistid'], pn=page)
                results = parse_singer_songs(datas)
                # insert_data(tablename='singer_song', datas=results)
                for result in results:
                    seed = {'_id': result['rid']}
                    get_music_info_20230512(seed)
            except Exception as e:
                print(e)
        print(artist, 'Done')
        global susccesslist
        susccesslist.append(artist)
    else:
        print('no {} data'.format(artist))
    song_info.close()
    pass




# 获取歌曲信息 run
def get_music_info_run():
    seeds = playlist_song_list.findAll({"status": None})
    lists =[]
    for seed in seeds[:]:
        lists.append(seed)
    print('playlist_song_list None:',len(lists))
    playlist_song_list.close()
    while len(lists)>0:
        print('--------------cishu--------------------')
        pool = Pool(processes=60)
        pool.map(get_music_info, lists)
        pool.close()  # 关闭进程池，不再接受新的进程
        pool.join()
        seeds = playlist_song_list.findAll({"status": None})
        lists = []
        for seed in seeds[:100]:
            lists.append(seed)
        playlist_song_list.close()




if __name__ == '__main__':

    # # run
    # 基于歌单更新歌曲列表
    # playlist_song_list_run()
    # # 基于歌手更新歌曲列表
    # singer_song_list_run()

    # 检查运行情况

    # # 下载歌曲信息
    # get_music_info_run()

    # test
    # test_20230512()
    lists2 = ['林俊杰', '陈奕迅', '张学友', '薛之谦', 'Beyond', '张杰', '王菲', '刘德华',
             '赵雷', '周传雄',
              'Michael Jakson'
               ]
    lists=['张韶涵','周华健',  '韩红', '满舒克', '梁静茹','陈势安', '许冠杰',
             '张楚生', '田馥甄', '杨培安', '信乐队',
              'MISSKO', '风凰传奇', '热狗',  '大冢爱','Professor Green ',
             'Charlie Puth','青鸟飞鱼'
           ]
    pool = Pool(processes=10)
    susccesslist=[]
    pool.map(test_20230512, lists)
    pool.close()  # 关闭进程池，不再接受新的进程
    pool.join()
    pass
